package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.MessagesApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Author 王加鑫
 * @Date 2021/09/06 17:56
 * @Since JDK 1.8
 */
@Service
public class QuanZiService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询好友动态
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //1、校验token获取user对象
        User user = UserThreadLocal.get();
        //2、去mongodb数据库查询出所有好友的Publish表的信息
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<QuanZiVo> quanZiVoList = saveQuanZiVoList(pageInfo,user);
        if(CollUtil.isEmpty(quanZiVoList)){
            return pageResult;
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 保存用户发布的动态
     * 用户在页面能输入的数据有： text文本内容，multipartFile照片，地址等
     * @param
     * @return
     */
    public String savePublish(String textContent,String location,String latitude,String longitude,MultipartFile[] multipartFile) {
        //校验token获取userId
        User user = UserThreadLocal.get();

        //查询用户发布动态是否被冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("3")){
            return "freeze";
        }

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLatitude(latitude);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        //图片上传需要使用阿里云的oss服务
        List<String> urls = new ArrayList<>();
        for (MultipartFile m : multipartFile) {
            String name = picUploadService.upload(m).getName();
            urls.add(name);
        }
        publish.setMedias(urls);
        //发布动态的操作
        String savePublish = quanZiApi.savePublish(publish);
        return savePublish;

    }

    /**
     * 查询推荐用户动态
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommend(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //校验token获取user对象
        User user = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = quanZiApi.queryRecommend(user.getId(),page,pageSize);
        List<QuanZiVo> quanZiVoList = saveQuanZiVoList(pageInfo,user);
        if(CollUtil.isEmpty(quanZiVoList)){
            return pageResult;
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 查询动态抽取公共工程
     * @param
     * @return
     */
    private List<QuanZiVo> saveQuanZiVoList(PageInfo<Publish> pageInfo,User user){
        //获取pageInfo里面所有的数据
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return null;
        }
        List<QuanZiVo> quanZiVoList = this.fillQuanZiVo(records);
        if(CollUtil.isEmpty(quanZiVoList)){
            return null;
        }
        return quanZiVoList;
    }

    /**
     * 点赞
     * @param commentId 评论表id
     * @return
     */
    public Long likeComment(String commentId) {
        //校验token获取user对象
        User user = UserThreadLocal.get();
        Boolean flag = quanZiApi.likeComment(user.getId(), commentId);
        if(flag){
            //如果点赞成功了，查询点赞数
            return this.quanZiApi.queryLikeCount(commentId);
        }
        return null;
    }

    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId) {
        //校验token获取user对象
        User user = UserThreadLocal.get();
        Boolean flag = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if(flag){
            //取消点赞成功
            return this.quanZiApi.queryLikeCount(publishId);
        }
        //取消点赞失败
        return null;
    }

    /**
     * 喜欢
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        //校验token
        User user = UserThreadLocal.get();
        Boolean flag = this.quanZiApi.loveComment(user.getId(),publishId);
        if(flag){
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    /**
     * 取消喜欢
     * @param publishId
     * @return
     */
    public Long disLoveComment(String publishId) {
        try {
            User user = UserThreadLocal.get();
            Boolean result = this.quanZiApi.disLoveComment(user.getId(), publishId);
            if(result){
                return this.quanZiApi.queryLoveCount(publishId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询单条动态信息
     * @param publishId
     * @return
     */
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        User user = UserThreadLocal.get();
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(user.getId());
        if(null != publish){
           return this.fillQuanZiVo(Arrays.asList(publish)).get(0);
        }
        return null;
    }


    /**
     * 填充QuanZiVo信息
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(DateTime.of(publish.getCreated()).toString());
            quanZiVoList.add(quanZiVo);
        });
        //获取到records里面所有userId
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        //根据userIds查询出所有用户数据
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        //获取当前登录对象
        User user = UserThreadLocal.get();
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfoList) {
                //判断条件：只有当userId相匹配了，才能将Publish表和UserInfo表中的数据整合到一起
                if(quanZiVo.getUserId() == userInfo.getUserId()){
                    quanZiVo.setTags(StringUtils.split(userInfo.getTags(),","));
                    quanZiVo.setGender(userInfo.getSex().getValue() == 1 ? "man":"woman");
                    quanZiVo.setAge(userInfo.getAge());
                    quanZiVo.setAvatar(userInfo.getLogo());
                    quanZiVo.setNickname(userInfo.getNickName());
                    quanZiVo.setCommentCount(0); //TODO 评论数
                    quanZiVo.setDistance("1.2公里"); //TODO 距离
                    quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(),quanZiVo.getId()) ? 1:0); //TODO 是否点赞（1是，0否）
                    quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
                    quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(),quanZiVo.getId()) ? 1:0); //TODO 是否喜欢（1是，0否）
                    quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
                    //跳出循环
                    break;
                }
            }
        }
        return quanZiVoList;
    }

    /**
     * 查询评论列表
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //查询mongodb中的Comment表中数据
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        User user = UserThreadLocal.get();
        //查询用户信息
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>().in("user_id", userIdList).orderByDesc("created");
        //查询mysql中的UserInfo表中数据
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        if(CollUtil.isEmpty(userIdList)){
            return pageResult;
        }

        //整合records，userInfoList数据到commentVoList中
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            //转换时间格式
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()),"HH:mm"));
            //是否点赞 userId:用户id publishId:用户的这条评论的id Comment表的id
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1:0); //1:点赞 0:没有点赞
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equal(record.getUserId(), userInfo.getUserId())){
                    //将用户在UserInfo表的其余数据封装进CommentVo表中
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            commentVoList.add(commentVo);
        }
        pageResult.setItems(commentVoList);
        return pageResult;
    }

    /**
     * 保存评论
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();

        //查询用户发言权限是否被冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("2")){
            return false;
        }

        return this.quanZiApi.saveComment(user.getId(), publishId, content);
    }

    /**
     * 询指定用户所有的动态
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    public PageResult queryAlbumList(Integer page, Integer pageSize, Long userId) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(page,pageSize,userId);
        //查询出指定用户的所有动态的信息
        List<Publish> publishList = pageInfo.getRecords();
        if(CollUtil.isEmpty(publishList)){
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = this.fillQuanZiVo(publishList);
        if(CollUtil.isEmpty(quanZiVoList)){
            return pageResult;
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 查询来访者
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if(CollUtil.isEmpty(visitorsList)){
            return Collections.emptyList();
        }

        //查询出来访者的id集合
        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }
}
